import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

import { options } from '../assets/college/data'
import styles from '../styles/Sell.module.scss'
import { useState } from 'react'

import Nav from '../components/Nav'
import { Cascader, Form, Input, Stepper, TextArea, Toast, } from 'antd-mobile'
import { AntOutline, AddCircleOutline } from 'antd-mobile-icons'
import { BookService, UserService } from '../services'

import UploadImg from '../components/UploadImg'
import { addProps, BookInfo } from '../services/book.service'
import { Warnicon, Winicon } from '../components/Icon'
import router from 'next/router'
import { IBooks } from '../models/types'
import { useMount } from 'ahooks'

interface Props {
  book: IBooks
  full: boolean
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const token = ctx.req.cookies?.token
  const res = await UserService.getuser(token)
  if (res?.stat !== 'OK')
    return {
      redirect: {
        destination: '/login',
        permanent: false
      }
    }
  const bookId = ctx.query.bookid as string
  if (bookId) {
    const bookRes = await BookService.detail(bookId)
    if (bookRes.stat === 'OK') {
      if (res.user._id !== bookRes.data.user._id)
        return {
          redirect: {
            destination: '/default',
            permanent: false
          }
        }
      return {
        props: {
          book: bookRes.data,
          full: true
        }
      }
    }
  }
  return {
    props: {
      full: false
    }
  }
}

const Sell: NextPage<Props> = ({ full, book }) => {
  const [isfull, setFull] = useState(full)
  const [visible, setVisible] = useState(false)
  const [value, setValue] = useState<string[]>([])
  const [form] = Form.useForm()

  const onSubmit = async () => {
    const values = form.getFieldsValue() as addProps

    // for (let index = 0; index < 5; index++) {
    const res = await BookService.addbook(values)

    // }
    if (res.stat === 'OK') {
      Toast.show({ content: <Winicon text='商品已提交审核' /> })
      router.push('/')
    } else {
      Toast.show({ content: <Warnicon text='请补全内容' /> })
    }
  }

  const onUpdate = async () => {
    const values = form.getFieldsValue() as addProps
    const res = await BookService.updatebook(book._id, values)
    if (res.stat === 'OK') {
      Toast.show({ content: <Winicon text='商品已更新' /> })
      router.back()
    } else {
      Toast.show({ content: <Warnicon text='请补全内容' /> })
    }
  }

  useMount(() => {
    if (book) form.setFieldsValue(book)
  })

  return (
    <div className="page">
      <Head>
        <title>发布商品页</title>
      </Head>
      <div className="wrap">
        {
          isfull ? <div className={styles.fixinfo}>
            <h3>上传书籍内容审核通过后才能进行出售</h3>
            <Form
              layout='horizontal'
              footer={
                <div className={styles.subwarp}>
                  <span
                    onClick={book ? onUpdate : onSubmit}
                    className={styles.submit}
                  >{book ? '更新' : '发布'}</span>
                </div>
              }
              initialValues={{
                books: [{
                  price: 5,
                  stock: 1,
                }]
              }}
              form={form}
            >
              <Form.Item name='title' label='标题' layout='vertical' >
                <Input
                  maxLength={20} min={2}
                  placeholder='请输入标题 例如:<<高数>> 跳楼大甩卖' clearable />
              </Form.Item>
              <Form.Item name='banner' label='封面' layout='vertical'>
                <UploadImg onChange={(value: string[]) => { }} max={6} />
              </Form.Item>
              <Form.Item
                label='所属专业'
                onClick={() => setVisible(true)}
                trigger='onConfirm'
                name='major'
                layout='vertical'
              >
                <Cascader
                  options={options}
                  visible={visible}
                  onClose={() => setVisible(false)}
                  value={value}
                  onConfirm={setValue}
                >
                  {items => {
                    if (items.every(item => item === null)) {
                      return '未选择'
                    } else {
                      return items.map(item => item?.label ?? '未选择').join('-')
                    }
                  }}
                </Cascader>
              </Form.Item>
              <Form.Array
                name='books'
                renderAdd={() => (
                  <span>
                    <AddCircleOutline /> 再卖一本
                  </span>
                )}
                renderHeader={({ index }, { remove }) => (
                  <>
                    <span>书籍{index + 1}</span>
                    <a onClick={() => remove(index)} style={{ float: 'right' }}>
                      删除
                    </a>
                  </>
                )}
              >
                {fields =>
                  fields.map(({ index }) => (
                    <>
                      <Form.Item name={[index, 'bookname']} label='书名' >
                        <Input placeholder='请输入书名' clearable />
                      </Form.Item>
                      <Form.Item name={[index, 'price']} label='书籍价格'
                        extra='单位(元)'>
                        <Input placeholder='价格: 最低5元' clearable type='number' min={5} defaultValue='5' />
                      </Form.Item>
                      <Form.Item name={[index, 'stock']} label='书籍数量:' >
                        <Stepper min={1} defaultValue={1} />
                      </Form.Item>
                    </>
                  ))
                }
              </Form.Array>
              <Form.Item name='content' required >
                <TextArea
                  placeholder='书籍简介, 目录,故事,用途'
                  showCount
                  maxLength={200}
                  rows={4}
                />
              </Form.Item>
            </Form>
          </div> : <main className={styles.nofull}>
            <div>
              <h2>1. 请完善个人信息后发布书籍</h2>
            </div>
            <div>
              <h2>2. 选择卖给网站(开发中)<br />&nbsp;&nbsp;&nbsp;&nbsp;选择自己挂网站售卖</h2>
            </div>
            <div>
              <h2>3. 审核通过后,书籍上线主页</h2>
            </div>
            {/* <span>卖给网站</span> */}
            <button onClick={() => setFull(true)}>出售书籍(个人)</button>
          </main>
        }
      </div>
      <Nav active={2} />
    </div>
  )
}

export default Sell
